//
//  ApplyInsuranceViewController.m
//  CPICApp
//
//  Created by sinosoft on 13-5-8.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "ApplyInsuranceViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "Config.h"
#import "RCAlertViewUtil.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"
#import "UIImageView+WebCache.h"
#import "IFServiceEvaluation.h"
#import "Appdelegate.h"
#import "OperationLogView.h"

@interface ApplyInsuranceViewController ()

@end

@implementation ApplyInsuranceViewController
@synthesize lblPhone,txtPhone,lblRemark,txvRemark,progress;
@synthesize strPolicyNo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title=@"续保申请";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"续保申请");
        //self.view.backgroundColor=[UIColor whiteColor];
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"续保申请");
        //self.view.backgroundColor=[UIColor whiteColor];
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"续保申请");
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }

    lblPhone=[[UILabel alloc]initWithFrame:CGRectMake(20, 10, 76, 21)];
    lblPhone.backgroundColor=[UIColor clearColor];
    lblPhone.text=@"联系电话:";
    
    txtPhone=[[UITextField alloc]initWithFrame:CGRectMake(100, 10, 179, 31)];
    txtPhone.borderStyle=UITextBorderStyleLine;
    txtPhone.delegate=self;
    CustomNumbleKeyboardView *customKeyboardView = [[CustomNumbleKeyboardView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 238)];
    customKeyboardView.delegate = self;
    [txtPhone setInputView:customKeyboardView];
    
    lblRemark=[[UILabel alloc]initWithFrame:CGRectMake(20, 10, 100, 21)];
    lblRemark.backgroundColor=[UIColor clearColor];
    lblRemark.text=@"续保内容:";
    
    txvRemark=[[UITextView alloc]initWithFrame:CGRectMake(20, 40, 278, 190)];
    txvRemark.backgroundColor=[UIColor clearColor];
    txvRemark.returnKeyType=UIReturnKeyDone;
    txvRemark.editable=YES;
    txvRemark.delegate=self;
    txvRemark.layer.borderColor = [UIColor grayColor].CGColor;
    txvRemark.layer.borderWidth =1.0;
    txvRemark.layer.cornerRadius =5.0;
    txvRemark.text=@"为方便快速有效的续保,请您留下联系时间及续保要求!";
    
    UIButton *btnAdd=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnAdd setTitle:@"提交" forState:UIControlStateNormal];
    btnAdd.frame=CGRectMake(86, 391, 310/2, 68/2);
    [btnAdd setBackgroundImage:[UIImage imageNamed:@"Submit_Book.png"] forState:UIControlStateNormal];
    [btnAdd addTarget:self action:@selector(submitApply) forControlEvents:UIControlEventTouchUpInside];
    
//    [self.view addSubview:lblPhone];
//    [self.view addSubview:txtPhone];
//    [self.view addSubview:lblRemark];
//    [self.view addSubview:txvRemark];
    [self.view addSubview:btnAdd];
    
    NSDictionary * dictCustomerInfo =[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_CUSTOMER_INFO];
    if (dictCustomerInfo!=nil)
    {
        if ([dictCustomerInfo valueForKey:@"phone"]) {
            self.txtPhone.text=[dictCustomerInfo valueForKey:@"phone"];
        }
    }
    else
    {

    }
    
    //添加UITableview
    TableInsurance = [[UITableView alloc]initWithFrame:CGRectMake(5, 51, 310, 350) style:UITableViewStyleGrouped];
    TableInsurance.dataSource = self;
	TableInsurance.delegate = self;
    
    TableInsurance.opaque = NO;
    TableInsurance.backgroundView = nil;
    TableInsurance.autoresizingMask = UIViewContentModeTop;
    TableInsurance.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    TableInsurance.scrollEnabled=NO;
    TableInsurance.backgroundColor=[UIColor clearColor];
    // [TableViewCarSetting reloadData];
	[self.view addSubview:TableInsurance];
}

#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 50;
    }
    else if(indexPath.row==1)
    {
        return 260;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *Identifier=@"Identifier";
    UITableViewCell *cell=(UITableViewCell *)[TableInsurance dequeueReusableCellWithIdentifier:Identifier];
    if (cell==nil)
    {
        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;//选中后颜色没变化
        
        
        if (indexPath.row == 0)
        {
            [cell addSubview:lblPhone];
            [cell addSubview:txtPhone];
        }
        else if(indexPath.row==1)
        {
            [cell addSubview:lblRemark];
            [cell addSubview:txvRemark];
        }
    }
    
    return cell;
}

//数字键盘
- (void)numberKeyBoardInput:(NSInteger) number
{
    NSMutableString *textString = [[[NSMutableString alloc] initWithFormat:@"%@%d",txtPhone.text,number] autorelease];
//    if ([textString length]>11)
//    {
//        [self justShowMessage:@"手机号码输入不能超过11位!" title:@""];
//        return;
//    }
    txtPhone.text = textString;
}

- (void)numberKeyBoardBackspace
{
    NSMutableString* mutableString = [[[NSMutableString alloc] initWithFormat:@"%@", txtPhone.text] autorelease];
    if ([mutableString length] >=1) {
        NSRange tmpRange;
        tmpRange.location = [mutableString length] - 1;
        tmpRange.length = 1;
        [mutableString deleteCharactersInRange:tmpRange];
    }
    txtPhone.text = mutableString;
    
}

- (void)numberKeyBoardFinish
{
    [txtPhone resignFirstResponder];
}
-(void)submitApply
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bContinueInsurance=TRUE;
    
    if (self.txtPhone.text.length==0) {
        [self justShowMessage:@"联系电话不能为空!" title:@"注意"];
        return;
    }
    if (self.txvRemark.text.length==0) {
        [self justShowMessage:@"备注不能为空!" title:@"注意"];
        return;
    }
    [self setApplyRequest];
}
-(void)setApplyRequest
{
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        return;
    }
    
    NSUserDefaults *myDefaultsCarInfo=[NSUserDefaults standardUserDefaults];
    NSDictionary *dictCarInfo=[myDefaultsCarInfo dictionaryForKey:DICT_CAR_CUSTOMERINFO];
    if (dictCarInfo!=nil)
    {

        if ([dictCarInfo valueForKey:@"policyHolder"]) {
            NSString *strPolicyHolder=[dictCarInfo valueForKey:@"policyHolder"];
            if ([strPolicyHolder isEqualToString:@""]) {
                [self justShowMessage:@"投保人为空,请到车辆设置页面去补充" title:@"注意"];
                return;
            }
        }else
        {
            [self justShowMessage:@"投保人为空,请到车辆设置页面去补充" title:@"注意"];
            return;
        }
    }
    else
    {
        [self justShowMessage:@"资料不完整,请到车辆设置页面去补充" title:@"注意"];
        return;
    }


    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    if (self.txtPhone.text.length!=0) {
        [dicRequest setValue:self.txtPhone.text forKey:@"telNo"];
    }
    else
    {
        [dicRequest setValue:@"" forKey:@"telNo"];
    }
    
    if (self.txvRemark.text.length!=0) {
        [dicRequest setValue:txvRemark.text forKey:@"market"];
    }
    else
    {
        [dicRequest setValue:@"" forKey:@"market"];
    }
    
    [dicRequest setValue:[dictUserInfo valueForKey:@"UserAccount"] forKey:@"userAccount"];
    [dicRequest setObject:[dictCarInfo valueForKey:@"policyHolder"] forKey:@"userName"];
    [dicRequest setObject:strPolicyNo forKey:@"policyNo"];
    
    NSString *strRequestJson=[dicRequest JSONRepresentation];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    [request setPostValue:@"63301" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseApplyFail:)];
    [request setDidFinishSelector:@selector(ResonseApplySuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseApplySuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    if ([strResult isEqualToString:@"1"]) {
        
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交续保申请成功,业务员会及时与你联系！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        alert.tag=1;
        alert.delegate = self;
        [alert release];
        return;
        
    }
    else
    {
        NSString *strMessage=[dictHead valueForKey:@"message"];
        [self justShowMessage:strMessage title:nil];
    }
    [strResult release];
    
    NSString *Code =@"63101";
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString * serialNostr=[accountDefaults objectForKey:@"OPERATIONLOG"];
    OperationLogView *operationlog =[[OperationLogView alloc]initView:Code withtype:@"2" withserialno:serialNostr];
    [operationlog setOperationLogRequest];
    [operationlog setHidden:YES];
    [self.view addSubview:operationlog];
    [operationlog release];
    
}

- (void)ResponseApplyFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==1) {
        if (buttonIndex==0) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}
-(void)SetAnimation:(CGFloat)Xorigin
{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    //frame.origin.x+=Xorigin;
    frame.origin.y-=Xorigin;
    //frame.size.height +=Xorigin;
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
}

-(void)backAnimation:(CGFloat)Xorigin
{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    //frame.origin.x -=Xorigin;
    frame.origin.y+=Xorigin;
    //frame.size.height -=Xorigin;
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
    // [textField resignFirstResponder];
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if(textView==txvRemark)
    {
        if ([txvRemark.text isEqualToString:@"为方便快速有效的续保,请您留下联系时间及续保要求!"]) {
            txvRemark.text=@"";
        }
        [self SetAnimation:130];
    }
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView==txvRemark)
    {
        [self backAnimation:130];
    }
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([@"\n" isEqualToString:text] == YES)
    {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}
-(void) ClickCallOutBtn
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc
{
    [lblPhone release];
    [txtPhone release];
    [lblRemark release];
    [txvRemark release];
    [strPolicyNo release];
    [super dealloc];
}
@end
